package org.example.zk3;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;

public class ZkServer {
    private String connectString = "192.168.110.97:2181,192.168.110.97:2182,192.168.110.97:2183";
    private int sessionTimeout = 10000;
    private ZooKeeper zooKeeper;
    private String serverZnode = "/servers";
    public static void main(String[] args) throws InterruptedException, IOException, KeeperException {
        ZkServer server = new ZkServer();
        server.init();
        server.regist(args[0]);
//        server.regist("server-info");
        server.waitFor();

    }

    private void waitFor() throws InterruptedException {
        Thread.sleep(Long.MAX_VALUE);
    }

    private void regist(String data) throws InterruptedException, KeeperException {
        Stat stat = zooKeeper.exists(serverZnode, false);
        if (stat == null) {
            zooKeeper.create(serverZnode, "servers".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

        }
        String s = zooKeeper.create(serverZnode + "/server", data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
        System.out.println("s = " + s);

    }

    private void init() throws IOException {
        zooKeeper = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {

            }
        });
    }
}
